import fg from "fast-glob";
import path from "path";
import { UnityHelper } from "./UnityHelper.js";
import { strArrayToMap } from "./vendor.js";
import { toolchain } from "../toolchain.js";

interface FontInfo {
    using: string[],
    useless: string[]
}

export class FontStriper {
    public async removeUseless(): Promise<void> {

        // 收集用到的guid
        //#region 
        const usedGUIDMap = await UnityHelper.collectUsedGUID(toolchain.opts.projectRoot);
        //#endregion

        const fontMap: { [dir: string]: FontInfo } = {};
        const fontRoot = path.join(toolchain.opts.projectRoot, 'Assets/AssetSources/font');
        const fonts = await fg(['**/*.fontsettings'], { cwd: fontRoot });
        for (const font of fonts) {
            const file = path.join(fontRoot, font);
            const guid = await UnityHelper.readGUID(file + '.meta');
            const d = path.dirname(file);

            let info = fontMap[d];
            if (info == null) fontMap[d] = info = { using: [], useless: [] };
            if (usedGUIDMap[guid]) {
                info.using.push(file);
            } else {
                info.useless.push(file);
            }
        }

        let cnt = 0;
        const manuals: string[] = [];
        for (const dir in fontMap) {
            if (fontMap[dir].using.length == 0) {
                await UnityHelper.removeDir(dir);
                cnt ++;
            } else {
                manuals.push(...fontMap[dir].useless);
            }
        }

        console.log(`${cnt} font dir removed`);
        console.warn('some dirs contains more than one font, you have to remove the following font by your hand:');
        manuals.forEach((v) => console.log(v));
    }
}
